'use client'

import { useState } from "react"
import { useRouter } from "next/navigation"

export default function AddTopic() {
    const [title, setTitle] = useState<string>("");
    const [description, setDescription] = useState<string>("");

    const router = useRouter();

    const handleSubmit = async (e: any) => {
        e.preventDefault();

        const res = await fetch("http://localhost:3000/api/topics", {
            method: "POST",
            headers: {
                "Content-Type": "application/json"
            },
            body: JSON.stringify({ title, description })
        });

        if (res.ok) {
            router.push("/");
        }
    }

    return (
        <form onClick={handleSubmit} className="flex flex-col gap-3">
            <input
                onChange={(e: any) => setTitle(e.target.value)}
                type="text"
                value={title}
                placeholder="Topic Title"
                className="border border-slate-500 px-8 py-2" />

            <input
                onChange={(e: any) => setDescription(e.target.value)}
                type="text"
                value={description}
                placeholder="Topic Description"
                className="border border-slate-500 px-8 py-2"
            />
            <button
                type="submit"
                className="bg-green-600 font-bold text-white py-3 px-6"
            >
                Add Topic
            </button>
        </form>
    )
}